package Admin;

import java.util.Random;
import javax.swing.*;

import lotterySystem.Show;
import lotterySystem.Winning;

import java.awt.BorderLayout;
import java.util.List;

//负责实现彩票抽奖的逻辑，包括生成中奖号码、比对用户选择的号码等


public class Rolling {
    
	//自动生成中奖号码
	public interface RollingCallback {
        void onRollingFinished(String winningNumber);
    }
	private static Thread rollingThread;
	private static JLabel numberLabel;
	private static String winningNumber;
    private static volatile boolean rolling = true; // 用于控制是否滚动
 
    public static String rolling(RollingCallback callback) {
        JFrame frame = new JFrame("抽奖游戏");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JButton startButton = new JButton("开始");
        JButton stopButton = new JButton("停止");

        numberLabel = new JLabel("", SwingConstants.CENTER);
        startButton.addActionListener(e -> {
            rolling = true;
            Thread rollingThread = new Thread(() -> {
                while (rolling) {
                    String number = generateWinningNumber();
                    displayRollingNumber(number); // 在屏幕上显示滚动中的号码
                    try {
                        Thread.sleep(100); // 模拟滚动速度
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
            });
            rollingThread.start();
        });

        stopButton.addActionListener(e -> {
            rolling = false; // 停止滚动
	        winningNumber = generateWinningNumber(); // 生成中奖号码
	 	    displayResult(winningNumber);
	 	    if (callback != null) {
	             frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                 callback.onRollingFinished(winningNumber);  // 调用回调函数通知抽奖结束
            }
        });
        
        if (rollingThread != null && rollingThread.isAlive()) { 
        	  try { 
                  rollingThread.join(); 
              } catch (InterruptedException ex) { 
                  ex.printStackTrace(); 
              }
              
              numberLabel.setText("");  // 清空号码显示

          }
   
    JPanel panel=new JPanel();
    panel.add(startButton);
    panel.add(stopButton);
    frame.add(panel, BorderLayout.SOUTH);
    
    frame.add(numberLabel, BorderLayout.CENTER);

    frame.setSize(300, 200);
    frame.setVisible(true);
    return  winningNumber;
    }

    public static void displayResult(String winningNumber) { 
        SwingUtilities.invokeLater(() -> numberLabel.setText("\n中奖号码是：【" +  winningNumber.replaceAll("(\\d{2})", "$1,") + "】"));
	 }// 在屏幕上展示中奖结果
	 
    public static void displayRollingNumber(String number) {
    	SwingUtilities.invokeLater(() -> numberLabel.setText("抽奖中：【" + number.replaceAll("(\\d{2})", "$1,")+ "】"));
	    }

    // 自动生成中奖号码
    public static String generateWinningNumber() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        
        for (int i = 0; i < 7; i++) {
            int number = random.nextInt(36) + 1;
            sb.append(String.format("%02d", number)); // 使用两位宽度格式化数字，并在前面补0
        }
        
        return sb.toString();
    }
  //判断中将号码是否合法
  	public static boolean setWinningNumber(String number) {

  		 if(!number.matches("\\d{14}")) {
  			JOptionPane.showMessageDialog(null, "号码不合法，请重新选择");
			return false;}
         for (int i = 0; i < number.length(); i += 2) {
            String subNum = number.substring(i, i + 2);
            int numValue = Integer.parseInt(subNum);
            if (numValue < 1 || numValue > 36) { 
            	JOptionPane.showMessageDialog(null, "号码不合法，请重新选择");
                return false; 
            }
         }
  	  		winningNumber = number;
  	  		JOptionPane.showMessageDialog(null, "设置成功，中将号码为：【"+winningNumber.replaceAll("(\\d{2})", "$1,")+ "】");
  			return true;
  		
  	}
    
    public static void createJframe(List<String> userRecords){
        
        JFrame frame = new JFrame("抽奖游戏");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JButton startButton = new JButton("开始");
        JButton stopButton = new JButton("停止");
        numberLabel = new JLabel("", SwingConstants.CENTER);
        startButton.addActionListener(e -> {
            rolling = true;
            Thread rollingThread = new Thread(() -> {
                while (rolling) {
                    String number = generateWinningNumber();
                    displayRollingNumber(number); // 在屏幕上显示滚动中的号码
                    try {
                        Thread.sleep(100); // 模拟滚动速度
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
            });
            rollingThread.start();
        });
        stopButton.addActionListener(e -> {
            rolling = false; // 停止滚动
	        winningNumber = generateWinningNumber(); // 生成中奖号码
	 	    displayResult(winningNumber);
	 	    // if (callback != null) {
	        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            JOptionPane.showMessageDialog(frame, "抽奖结束，中奖号码："+ winningNumber);
            Show.displayWinnerInfos(Winning.checkWinning(userRecords, winningNumber),winningNumber);
            // 继续执行其他逻辑...
                
            //  callback.onRollingFinished(winningNumber);  // 调用回调函数通知抽奖结束
            // }
            if (rollingThread != null && rollingThread.isAlive()) { 
                try { 
                    rollingThread.join(); 
                } catch (InterruptedException ex) { 
                    ex.printStackTrace(); 
                }
                
                numberLabel.setText("");  // 清空号码显示
    
            }
        });
      
       
        JPanel panel=new JPanel();
        panel.add(startButton);
        panel.add(stopButton);
        frame.add(panel, BorderLayout.SOUTH);
        
        frame.add(numberLabel, BorderLayout.CENTER);
    
        frame.setSize(300, 200);
        frame.setVisible(true);
        return;
    }
    
}
